<?php

/**
 *  员工管理逻辑表
 */

namespace app\admin\service;

use app\facade\Basic;
use app\admin\model\Operator as OperatorModel;
use think\facade\Config;
use app\admin\common\ServiceResponse;
use app\admin\service\Department;
use app\admin\model\Role as ModelRole;

class Operator extends BaseService
{

    use ServiceResponse;

    protected $model;
    public function __construct()
    {
        parent::__construct();
        $this->model = new OperatorModel();
    }


    /**
     *  员工列表
     */
    public function getList(array $where, int $page, int $limit)
    {

        if (isset($where['department']) && $where['department'] > 0) {
            $departmentService = new Department();
            $department = $departmentService->getAllDepartmentId($where['department']);

            if (0 == $department['code']) {
                $where[] = ['department', 'in', implode(',', $department['data']['list'])];
                unset($where['department']);
            }
        }

        $total = $this->model->where($where)->count();

        // 获取角色列表
        $roleList = [];
        $roles = ModelRole::field('id,name')->select()->toArray();
        foreach ($roles as $role) {
            $roleList[$role['id']] = $role['name'];
        }

        $data = $this->model
            ->with([
                'department' => function ($query) {
                    $query->field('id, name');
                }
            ])
            ->field('id,cname,phone,email,nickname,department,position,login_num,create_time,last_login_time,last_ip,status,remark,isadmin,roles,job')
            ->page($page, $limit)
            ->where($where)
            ->order("id DESC")
            ->select()
            ->toArray();
        $jobList = $this->model->getAttributesMap()['jobs'];
        foreach ($data as $key => $value) {
            // 处理角色文本
            $value['roles_txt'] = '';
            if (!empty($value['roles'])) {
                $roles = explode(',', $value['roles']);
                foreach ($roles as $v) {
                    $v = trim($v);
                    if ($v && isset($roleList[$v])) {
                        $value['roles_txt'] .= $roleList[$v] . ',';
                    }
                }
            }
            $value['roles_txt'] = $value['roles_txt'] ? rtrim($value['roles_txt'], ',') : '';

            // 处理职位文本
            $value['job_txt'] = '';
            if (!empty($value['job'])) {
                $jobs = explode(',', $value['job']);
                foreach ($jobs as $v) {
                    $v = trim($v);
                    if ($v && isset($jobList[$v])) {
                        $value['job_txt'] .= $jobList[$v] . ',';
                    }
                }
            }
            $value['job_txt'] = $value['job_txt'] ? rtrim($value['job_txt'], ',') : '';

            $data[$key] = $value;
        }


        $data = ['list' => $data, 'total' => $total];
        return $this->success($data);
    }

    /**
     *  员工详情
     */
    public function detail($param)
    {
        $result = $this->model
            ->with([
                'department' => function ($query) {
                    $query->field('id, name');
                }
            ])
            ->where('id', $param['id'])
            ->field('id,cname,phone,email,nickname,department,login_num,create_time,last_login_time,last_ip,status,remark,isadmin,roles,abbr,job')
            ->find();
        // 获取角色列表
        $roleList = [];
        $roles = ModelRole::field('id,name')->select()->toArray();
        foreach ($roles as $role) {
            $roleList[$role['id']] = $role['name'];
        }

        // 获取职位列表
        $jobList = $this->model->getAttributesMap()['jobs'];

        $result->isadmin = (int) $result->isadmin;
        $result->position = (int) $result->position;

        $role_txt = '';
        $r = []; // 初始化角色数组
        if (isset($result->roles)) {
            $rolesArr = explode(',', $result->roles);
            foreach ($rolesArr as $v) {
                $v = trim($v); // 去除空格
                if (!$v) continue; // 跳过空值

                $roleId = (int) $v;
                $r[] = $roleId; // 使用连续索引

                if (isset($roleList[$roleId])) {
                    $role_txt .= $roleList[$roleId] . ',';
                }
            }

            $result->roles = $r;
            // 安全地处理角色文本，避免空字符串的substr问题
            $result->roles_txt = $role_txt ? rtrim($role_txt, ',') : '';
        } else {
            $result->roles = [];
        }
        $job_txt = '';
        $j = []; // 初始化职位数组
        if (isset($result->job)) {
            $jobsArr = explode(',', $result->job);
            foreach ($jobsArr as $v) {
                $v = trim($v); // 去除空格
                if (!$v) continue; // 跳过空值

                $jobId = (int) $v;
                $j[] = $jobId; // 使用连续索引

                if (isset($jobList[$jobId])) {
                    $job_txt .= $jobList[$jobId] . ',';
                }
            }

            $result->job = $j;
            // 安全地处理职位文本，避免空字符串的substr问题
            $result->job_txt = $job_txt ? rtrim($job_txt, ',') : '';
        } else {
            $result->job = [];
        }

        $result = $result->toArray();

        if (is_array($result['department'])) {
            $result['department_obj'] = $result['department'];
            $result['department'] = $result['department']['id'];
        }


        if ($result) {
            return Basic::data(0, 'ok', $result);
        } else {
            return Basic::data(1, '用户不存在');
        }
    }

    /**
     *  获取权限
     */
    public function getFieldEnum($field = 'all')
    {
        //db_role
        $result = ModelRole::where('status', '=', 1)
            ->where('is_del', '=', '0')
            ->field('id,name')
            ->select();
        $role = [];
        foreach ($result as $value) {
            $role[] = [
                'value' => $value['id'],
                'label' => $value['name']
            ];
        }
        if (empty($field)) $field = 'all';
        $enum = $this->model->getFieldEnum($field);
        $res = array_merge(['roles' => $role], $enum);
        return Basic::data(0, 'ok', $res);
    }


    /**
     *  员工信息更新
     */
    public function save($param)
    {
        $insData = [];
        $insData['id'] = $param['id'];
        $insData['cname'] = $param['cname'];
        $insData['phone'] = $param['phone'];
        $insData['email'] = $param['email'];
        $insData['nickname'] = $param['nickname'];
        $insData['department'] = $param['department'];
        $insData['position'] = $param['position'];
        $insData['status'] = $param['status'];
        $insData['remark'] = $param['remark'];
        $insData['isadmin'] = $param['isadmin'];
        $insData['create_time'] = date('Y-m-d H:i:s');
        $insData['roles'] = $param['role'];
        $insData['job'] = $param['job'];

        /* 密码 */
        if (!empty($param['password'])) {

            $password_salt = Config::get('operator.password_salt');
            $create_time = $insData['create_time'];
            $password = $param['password'];
            $insData['password'] = md5(md5($password . $password_salt . $create_time));
        }

        if (empty($insData['id'])) {
            unset($insData['id']);

            /* 查询用户是否存在 */
            if (!empty($insData['cname'])) {
                $whereOr['cname'] = $insData['cname'];
            }

            if (!empty($insData['phone'])) {
                $whereOr['phone'] = $insData['phone'];
            }

            if (!empty($insData['email'])) {
                $whereOr['email'] = $insData['email'];
            }


            if (OperatorModel::whereOr($whereOr)->find()) {
                return Basic::data(1, '该用户已存在');
            }

            $result = OperatorModel::create($insData);
            if ($result) {
                $this->logger->logOperation($result->id, 'Operator', '创建', '创建员工');
                return Basic::data(0, '保存成功');
            } else {
                return Basic::data(1, '保存失败');
            }
        } else {
            $result = OperatorModel::update($insData);
            if ($result) {
                $this->logger->logOperation($result->id, 'Operator', '修改', '修改员工');
                return Basic::data(0, '修改成功');
            } else {
                return Basic::data(1, '修改失败');
            }
        }
    }

    /**
     *  分配角色
     */
    public function assignRole($param)
    {
        $role_ids = $param['role_ids'];

        if (is_array($role_ids)) {
            $roles = implode(',', $role_ids);
            $result = OperatorModel::where('id', $param['id'])->update(['roles' => $roles]);
            if ($result) {
                $this->logger->logOperation($result->id, 'Operator', '分配', '分配角色');
                return Basic::data(0, '保存成功');
            } else {
                return Basic::data(1, '保存失败');
            }
        } else {
            return Basic::data(1, 'auth_ids 格式错误');
        }
    }


    /**
     *  移出员工
     */
    public function remove($param)
    {

        $result = OperatorModel::where('id', $param['id'])->find();

        if (!$result) {
            return Basic::data(0, '用户不存在');
        }

        if ($result->is_del != 0) {
            return Basic::data(0, '已经被删除');
        }

        $result->is_del = time();
        $result->update_time = date("Y-m-d H:i:s");

        if ($result->save()) {
            $this->logger->logOperation($result->id, 'Operator', '删除', '删除员工');
            return Basic::data(0, '删除成功');
        } else {
            return Basic::data(1, '删除失败');
        }
    }

    /**
     *  删除员工
     */
    public function del($param)
    {

        $count = OperatorModel::where('id', 'in', $param['ids'])
            ->where('is_del', '=', 0)
            ->field('id')
            ->count();

        if ($count != count($param['ids'])) {
            return Basic::data(0, '用户不存在');
        }


        $result = OperatorModel::where('id', 'in', $param['ids'])->update([
            'is_del' => time()
        ]);

        $this->logger->logOperation($param['ids'], 'Operator', '删除', '删除员工');

        if ($result) {
            return Basic::data(0, '删除成功');
        } else {
            return Basic::data(1, '删除失败');
        }
    }

    /**
     * 创建管理员
     */
    public function create($param)
    {


        $operator = OperatorModel::where('cname', $param['cname'])
            ->whereOr('phone', $param['phone'])
            ->whereOr('email', $param['email'])
            ->where('is_del', '=', 0)
            ->find();

        if ($operator) {
            return Basic::data(1, '该用户已存在');
        }

        $data = [];
        $data['create_time'] = date('Y-m-d H:i:s');

        if (isset($param['cname'])) {
            $data['cname'] = $param['cname'];
        } else {
            return Basic::data(1, '用户不存在');
        }

        if (isset($param['phone'])) {
            $data['phone'] = $param['phone'];
        } else {
            return Basic::data(1, '电话不存在');
        }

        if (isset($param['email'])) {
            $data['email'] = $param['email'];
        } else {
            return Basic::data(1, 'Emial不存在');
        }

        $data['nickname'] = $param['nickname'] ?? '';
        $data['department'] = $param['department'] ?? '';
        $data['status'] = $param['status'] ?? '';
        $data['remark'] = $param['remark'] ?? '';
        $data['abbr'] = $param['abbr'] ?? '';

        if (isset($param['roles'])) {
            $data['roles'] = implode(",", $param['roles']);
        } else {
            $data['roles'] = null;
        }

        $result = OperatorModel::create($data);

        if ($result) {
            $this->logger->logOperation($result->id, 'Operator', '新增管理员', '新增管理员');
            return Basic::data(0, '添加成功');
        } else {
            return Basic::data(1, '添加失败');
        }
    }


    /**
     * 更新部门
     * @param int $id 部门ID
     * @param array $data 更新部门的数据
     */
    public function update($params)
    {

        $operator = OperatorModel::where('id', $params['id'])->find();

        foreach ($params as $key => $value) {
            if ($operator->$key != $value) {
                $operator->$key = $value;
            }
        }

        if (isset($params['roles'])) {
            $operator->roles = implode(",", $params['roles']);
        } else {
            $operator->roles = null;
        }

        if (isset($params['job'])) {
            $operator->job = implode(",", $params['job']);
        } else {
            $operator->job = null;
        }

        $result = $operator->save();
        if ($result) {
            $this->logger->logOperation($operator->id, 'Operator', '更新', '更新员工信息');
            return Basic::data(0, '更新成功');
        } else {
            return Basic::data(1, '更新失败');
        }
    }

    public function getSelect($operator_id = 0)
    {
        $where = [['is_del', '=', 0]];
        $arrData = ['code' => 0, 'message' => 'success'];

        $oCategoryModel = OperatorModel::where($where);
        $total = $oCategoryModel->count();
        $result = $oCategoryModel->field('id AS value,cname as label')->select();

        foreach ($result as $key => $value) {
            if ($value['value'] == $operator_id) {
                $result[$key]['selected'] = true;
            }
        }

        $arrData['data'] = ['list' => $result->toArray(), 'total' => $total];

        return $arrData;
    }


    /**
     * @describe 获取销售相关的客户信息
     * @author: Bobo
     * @date: 2024-12-17 15:58:18
     * @param [int] @required $operator_id 员工ID
     * @return Renderable
     */
    public function getBelongCustomers(int $operator_id = 0)
    {
        if (!$operator_id || !is_numeric($operator_id)) {
            return $this->error(100001);
        }
        $data = [];
        $order_range = ['order_range' => 1];
        $role = $this->model->where('id', $operator_id)->value('roles');
        if ($role) {
            $order_range = $this->model->name('role')->where('id', 'in', $role)->field('MAX(order_range) as order_range')->find()->toArray();
        }

        if (1 == $order_range['order_range']) {
            $data = $this->model
                ->name('customer')
                ->where(['is_del' => 0])
                ->whereRaw("owner = {$operator_id} OR FIND_IN_SET('{$operator_id}', partner)")
                ->field('id')
                ->select()
                ->toArray();
        }

        if (empty($data)) {
            $customer_ids = [0];
        } else {
            $customer_ids = array_column($data, 'id');
        }
        return $this->success([
            'customer_ids' => $customer_ids,
            'order_range' => $order_range['order_range']
        ]);
    }


    /**
     *  获取用户名称列表
     */
    public function getOperatorName(array $ids = [])
    {

        $where['is_del'] = 0;
        if ($ids) {
            $where['id'] = ['in', $ids];
        }

        $result = OperatorModel::where($where)->field('id,cname')->select();

        $operator = [];
        foreach ($result as $key => $value) {
            $operator[$value->id] = $value->cname;
        }
        return $operator;
    }
}
